package com.chen.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.reggie.common.R;
import com.chen.reggie.entity.Category;
import com.chen.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("page")
    private R<Page> page(int page, int pageSize) {
//        log.info("{},{},{}",page,pageSize);
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(categoryPage, queryWrapper);

        return R.success(categoryPage);
    }

    /**
     * 新增分类
     */
    @PostMapping
    private R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("操作成功");

    }

    /**
     * 删除分类
     */
    @DeleteMapping
    private R<String> delete(Long ids) {
        //查询该分类是否关联菜品或者套餐
        categoryService.remove(ids);
        return R.success("操作成功");
    }

    /**
     * 修改分类
     */
    @PutMapping
    private R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("操作成功");
    }

    /**
     * 根据条件查询分类
     */
    @GetMapping("list")
    private R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryService.list(queryWrapper);
        return R.success(categoryList);
    }

}
